#include "imageprint.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QPainter>
#include <QPrinter>
#include <QPrintDialog>

ImagePrint::ImagePrint(QWidget* parent) :
    QDialog(parent), imgLabel(new QLabel(this))
{
    setWindowTitle("图片打印");
    setFixedSize(500, 400);

    QVBoxLayout* layout = new QVBoxLayout(this);
    QPushButton* loadBtn = new QPushButton("加载图片", this);
    QPushButton* printBtn = new QPushButton("打印图片", this);
    layout->addWidget(loadBtn);
    layout->addWidget(printBtn);
    layout->addWidget(imgLabel);


    connect(loadBtn, &QPushButton::clicked, this, &ImagePrint::loadImage);
    connect(printBtn, &QPushButton::clicked, this, &ImagePrint::printImage);
}

ImagePrint::~ImagePrint()
{

}

void ImagePrint::loadImage()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Open Image", "", "Images (*.png *.jpg *.jpeg *.bmp *.gif)");
    if (!fileName.isEmpty()) {
        if (currentImage.load(fileName)) {
            imgLabel->setPixmap(QPixmap::fromImage(currentImage));
            imgLabel->setScaledContents(true); // 使 QLabel 自适应图片大小
            //imgLabel->setFixedSize(400, 300); // 设置 QLabel 固定大小
        }
    }
}

void ImagePrint::printImage()
{
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName("img.pdf");
    printer.setPageMargins(QMarginsF(0,0,0,0));
    QPainter painter;
    painter.begin(&printer);

    double xscale = printer.pageRect().width();
    double yscale = printer.pageRect().height() ;
    double scale = qMin(xscale, yscale);
    QPixmap pixmap =  QPixmap::fromImage(currentImage).scaled(scale, scale, Qt::KeepAspectRatio, Qt::FastTransformation);
    painter.drawPixmap (0, 0, pixmap.scaled(scale, scale / 2));
    painter.end();
    QPrintDialog dialog(&printer);
    dialog.exec();
}
